<template>

  <div>
      <el-card class="member-box-card">
        <el-input id="input-field" v-model="search" size="mini" placeholder="输入物料名称进行搜索"/>
        <el-table id="member-table" ref="memberTable" :key="itemKey" v-loading="loading"  border height="700"
                  style="width: 100%" :data="searchHandler()" max-height="450">
          <el-table-column prop="id" label="序号"/>
          <el-table-column prop="name" label="物资名称"/>
          <el-table-column prop="specification" label="型号及规格"/>
          <el-table-column prop="unit" label="计量单位"/>
          <el-table-column prop="type" label="物料类型"/>
          <el-table-column align="right">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleQRcode(scope.$index, scope.row)">导出二维码</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    <div id="qrcode"></div>
  </div>

</template>

<script>
  import { allmaterials, searchbyname } from '@/api/entrywarehouse/base-information'
  import { getToken } from '@/utils/auth'
  import QRCode from 'qrcodejs2'

  export default {
    data() {
      return {
        tableData: [],
        search: '',
        itemKey: '',
        loading: false,
        headers: {
          Authorization: getToken()
        }
      }
    },
    created() {
      this.init()
    },
    methods: {
      init() {
        allmaterials().then((response) => {
          this.tableData = response.data
        })
      },
      searchHandler() {
        return this.tableData.filter(data => !this.search || data.name.toLowerCase().includes(this.search.toLowerCase()))
      },
      // 生成二维码
      qrcode(index, row){
        let qrcode = new QRCode('qrcode', {
          width: 200,
          height: 200, // 高度
          text:'{' + '\r\n' + 'name: ' + row.name + ','  + '\r\n'+ 'specification: ' + row.specification + ','  + '\r\n'+
            'unit: ' + row.unit + ','  + '\r\n'+ 'type: '+ row.type + '}'
        })
      },
      // 下载二维码
      handleQRcode(index, row){
        this.qrcode(index, row); //下载之前首先要有二维码
        // 先找到canvas节点下的二维码图片
        let myCanvas = document.getElementById('qrcode').getElementsByTagName('canvas');
        let img=document.getElementById('qrcode').getElementsByTagName('img');
        // 创建一个a节点
        let a = document.createElement('a');
        // 设置a的href属性将canvas变成png格式
        let imgURL=myCanvas[0].toDataURL('image/jpg');
        let ua = navigator.userAgent;
        if (ua.indexOf("Trident") != -1 && ua.indexOf("Windows") != -1) { // IE内核 并且  windows系统 情况下 才执行;
          var bstr = atob(imgURL.split(',')[1])
          var n = bstr.length
          var u8arr = new Uint8Array(n)
          while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
          }
          var blob = new Blob([u8arr])
          window.navigator.msSaveOrOpenBlob(blob, row.name + '.' + 'png')
        }else if(ua.indexOf("Firefox") > -1){ //火狐兼容下载
          let blob = this.base64ToBlob(imgURL); //new Blob([content]);
          let evt = document.createEvent("HTMLEvents");
          evt.initEvent("click", true, true);//initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
          a.download = ' ';//下载图片名称，如果填内容识别不到，下载为未知文件，所以我这里就不填为空
          a.href = URL.createObjectURL(blob);
          a.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));//兼容火狐
        }else{ //谷歌兼容下载
          img.src=myCanvas[0].toDataURL('image/jpg');
          // a.href = myCanvas[0].toDataURL('image/png').replace('image/png', 'image/octet-stream')
          a.href=img.src
          //设置下载文件的名字
          a.download = "下载"
          //点击
          a.click()
        }
      },

      //base64转blob
      base64ToBlob(code) {
        let parts = code.split(';base64,');
        let contentType = parts[0].split(':')[1];
        let raw = window.atob(parts[1]);
        let rawLength = raw.length;
        let uInt8Array = new Uint8Array(rawLength);
        for (let i = 0; i < rawLength; ++i) {
          uInt8Array[i] = raw.charCodeAt(i);
        }
        return new Blob([uInt8Array], {type: contentType});
      }

    }

  }

</script>

<style >
  .member-box-card {
    width: 95%;
    margin: 20px auto;
  }
  #input-field {
    width: 200px;
    display: inline;
  }
  #member-table {
    margin-top: 5px;
  }
  .action-form {
    width: 400px;
  }
</style>
